import React,{useState,useRef,useEffect } from 'react';
import type { SelectProps } from 'antd';
import { flushSync } from 'react-dom';
import {Select,Space,DatePicker,Row,Col,Button} from 'antd'
import {DownOutlined,UpOutlined,SearchOutlined,ReloadOutlined } from '@ant-design/icons';
import {selectItemType,SelectPropsType,selectRangePickerType,paramDataType} from './../data'
import styles from './../index.less'
import { template } from 'lodash';
import moment from 'moment'
import dayjs from 'dayjs';
import {cloneDeep} from 'lodash'
import {getTHBTime , isCurrent} from '../../../utils/methods'
const { RangePicker } = DatePicker;

function SearchArea(props) {
  const defaultStyle = {
    transition: `heigth 3s ease`,
  }
  const GoSearch = props.onSearch
  const [showMore,setShowMore] = useState(false)
  const [conStyle,setConStyle] = useState({height:'40px',overflow:'hidden',...defaultStyle})
  const dateFormat = 'YYYY-MM-DD'
  const [dateType, setDateType] = useState('month');
  const [date_type, setDate_type] = useState('month');
  const [compType, setCompType] = useState('1');
  const [nowDateS, setNowDateS] = useState(dayjs().subtract(1, 'day'));
  const [nowDateE, setNowDateE] = useState(dayjs().subtract(1, 'day'));
  const [dateS, setDateS] = useState(dayjs().subtract(1, 'day'));
  const [dateE, setDateE] = useState(dayjs().subtract(1, 'day'));
  const [dateYS, setDateYS] = useState(dayjs().subtract(1, 'day'));
  const [dateYE, setDateYE] = useState(dayjs().subtract(1, 'day'));

  useEffect(()=>{
    let start = dayjs(nowDateS).startOf(date_type)
    let end = dayjs(nowDateE)
    if(compType == '1'){
      start = dayjs(nowDateS).startOf(date_type)
      end = dayjs(nowDateE).endOf(date_type)
    }else{
      start = dayjs(nowDateS).startOf(date_type)
      let isZQ = isCurrent(nowDateE,date_type)
      if(isZQ){
        end = dayjs(nowDateE)
      }else{
        end = dayjs(nowDateE).endOf(date_type)
      }
    }
    setDateS(start)
    setDateE(end)
  },[nowDateS,nowDateE,compType])

  useEffect(()=>{
    if(compType == '1'){
      setDateYS(cloneDeep(dayjs(dateS).subtract(1,'year')))
      let end = getTHBTime(compType,[dayjs(dateS).format(dateFormat),dayjs(dateE).format(dateFormat)],dateType,dayjs(dateS).subtract(1,'year'))
      setDateYE(cloneDeep(dayjs(end)))
    }else{
      setDateYE(cloneDeep(dayjs(dateS).subtract(1,'day')))
      let start = getTHBTime(compType,[dayjs(dateS).format(dateFormat),dayjs(dateE).format(dateFormat)],dateType,dayjs(dateS).subtract(1,'day'))
      setDateYS(cloneDeep(dayjs(start)))
    }
  },[dateS,dateE])

  useEffect(()=>{
    console.log('dateYS',dayjs(dateYS).format(dateFormat))
    console.log('dateYE',dayjs(dateYE).format(dateFormat))
    console.log('compType',compType)

  },[dateYS,dateYE,compType])
  
 
  let params = {
    dateS,
    dateE,
    dateYS,
    dateYE,
    nowDateS,
    nowDateE,
    compType,
    dateType,
  }
  let initParams:paramDataType ={
    'comp_type':compType,
    'contrast_date':[dayjs(dateYS).format(dateFormat),dayjs(dateYE).format(dateFormat)],  
    'date_pick':[],
    'date_type':dateType,
    "value_time":[dayjs(dateS).format(dateFormat),dayjs(dateE).format(dateFormat)],
  }
  const [paramsData,setParams] = useState({...initParams})
  
  //视角
  const selectSJData:SelectPropsType={
    style: { width: '120px' },
    value:'jack',
    options:[
      { value: 'jack', label: 'Jack' },
      { value: 'lucy', label: 'Lucy' },
      { value: 'Yiminghe', label: 'yiminghe' },
      { value: 'disabled', label: 'Disabled', disabled: true },
    ],
    placeholder:'请选择视角',
    onChange:(newValue: string) => {
      handleSJChange(newValue)
    },
  }
  const handleSJChange = (value: string)=>{
    console.log(`handleChange${value}`)
  }
  //品牌
  interface ItemProps {
    label: string;
    value: string;
  }
  const options: ItemProps[] = [];
  for (let i = 10; i < 36; i++) {
    const value = i.toString(36) + i;
    options.push({
      label: `Label: ${value}`,
      value,
    });
  }
  const selectData = {
    mode:'multiple',
    style: { width: '200px' },
    value:['a10', 'c12', 'h17', 'j19', 'k20'],
    options:options,
    placeholder:'请选择',
    maxTagCount: 1,
    onChange:(newValue: string[]) => {
      selectChange(newValue)
    },
  }
  const selectChange = (value: string[])=>{
       console.log('selectChange',value)
  }
  //日期类型
  const selectDateTypeData:SelectPropsType={
    style: { width: '80px' },
    value: dateType,
    options:[
      { value: 'date', label: '日' },
      { value: 'week', label: '周' },
      { value: 'month', label: '月'},
      { value: 'quarter', label: '季'},
      { value: 'year', label: '年'},
    ],
    placeholder:'请选择日期类型',
    onChange:(newValue: string) => {
      setDateType(newValue)
      setDate_type(newValue == 'date'?'day':newValue)
      console.log(dateE,dateS)
      let days = dayjs(dateE).diff(dayjs(dateS),newValue)
      console.log('days',days)
      switch(newValue){
        case 'date':

          break;
        case 'week':
          break;
        case 'month':
          break;
        case 'quarter':
          break;
        case 'year':
          break;
      }
    },
  }
  //现在时间
  let selectRangePicker:selectRangePickerType={
      type: dateType,
      style: { width: '340px' },
      onChange:(newValue:any,key:string) => {
         switch(key){
          case 'StartTHB':
            console.log('StartTHB---',dayjs(newValue).format(dateFormat))
            setDateYS(dayjs(newValue))
            let aa =getTHBTime(compType,[dayjs(dateS).format(dateFormat),dayjs(dateE).format(dateFormat)],dateType,dayjs(newValue))
            setDateYE(dayjs(aa))
          break;
          case 'EndTHB':
            console.log('EndTHB---',dayjs(newValue).format(dateFormat))
            setDateYE(dayjs(newValue))
            let bb = getTHBTime(compType,[dayjs(dateS).format(dateFormat),dayjs(dateE).format(dateFormat)],dateType,dayjs(newValue))
            setDateYS(dayjs(bb))
          break;
          case 'RangePicker':
            console.log('RangePicker---',dayjs(newValue[0]).format(dateFormat),dayjs(newValue[1]).format(dateFormat))
            setNowDateS(dayjs(newValue[0]))
            setNowDateE(dayjs(newValue[1]))
            let isZQ = isCurrent(newValue[1],date_type)
            let start = dayjs(newValue[0]).startOf(date_type)
            let end = dayjs(newValue[1])
            if(isZQ){
              end = dayjs(newValue[1])
            }else{
              end = dayjs(newValue[1]).endOf(date_type)
            }
            setDateS(start)
            setDateE(end)
          break; 
          default :
        }
      },
  }

  //切换同环比
  let selectCompTypeData:SelectPropsType={
    style: { width: '100px' },
    value: compType,
    options:[//comp_type =1同比。 2环比。
      {label:'同比',value:'1'},
      {label:'环比',value:'2'}
    ],
    placeholder:'请选择时间类型',
    onChange:(newValue: string) => {
      setCompType(newValue)
    },
  }
  //搜索
  let searchData = [
    {
      type:'select',
      mode:'sigel',
      key:'selectSJ',
      data:selectSJData,
    },
    {
      type:'select',
      mode:'multiple',
      key:'selectPP',
      data:selectData,
    },
    {
      type:'select',
      mode:'singel',
      key:'selectDateType',
      data:selectDateTypeData,
    },
    {
      type:'RangePicker',
      mode:'',
      key:'RangePicker',
      data:selectRangePicker,
      value:[dateS,dateE]
    },
    {
      type:'select',
      mode:'singel',
      key:'selectCompType',
      data:selectCompTypeData,
    },
    {
      type:'DateRange',
      mode:'',
      key:'DateRange',
      data:[
        {
          mode:'',
          key:'StartTHB',
          data:{...selectRangePicker,style: { width: '200px' }},
          value:dateYS,
        },
        {
          mode:'',
          key:'EndTHB',
          data:{...selectRangePicker,style: { width: '200px' }},
          value:dateYE,
        }
      ],
    },
  ]
  const onSearch =()=>{
      let data ={
        'comp_type':params.compType,
        'contrast_date':[dayjs(params.dateYS).format(dateFormat),dayjs(params.dateYE).format(dateFormat)],  
        'date_pick':[],
        'date_type':params.dateType,
        "value_time":[dayjs(params.dateS).format(dateFormat),dayjs(params.dateE).format(dateFormat)],
      }
      setParams({...data})
      console.log('data----',data)
      return GoSearch(data)
  }
  const onReset=()=>{
    setParams({...initParams})
  }

  const changeMore = ()=>{
    setShowMore(!showMore)
  }
  useEffect(()=>{
    if(showMore){
      setConStyle({height:'auto',overflow:'auto',...defaultStyle})
    }else{
      setConStyle({height:'40px',overflow:'hidden',...defaultStyle})
    }
  },[showMore])
  
  return (
    <Row className={styles.SearchArea}>
      <Col span={18}>
        <Space wrap size="middle" style={conStyle}>
          {
            searchData !== undefined && searchData.length>0 && 
            searchData.map((item,ind)=>{
              if(item.type === 'select'){
                let selectData ={
                  mode:item.mode,
                  style:item.data.style,
                  value:item.data.value,
                  options:item.data.options,
                  placeholder:item.data.placeholder,
                  maxTagCount: item.data.maxTagCount || 1,
                  onChange:(newValue) => {
                    return item.data.onChange(newValue)
                  },
                }
                return(
                  <Select key={item.key+'_'+ind+item.data.value} {...selectData}/>
                )
              }else if( item.type === 'RangePicker'){
                return (
                  <RangePicker 
                    key={item.key+'_'+ind+dateS+dateE}  
                    defaultValue={[dateS,dateE]}
                    picker={item.data.type} 
                    style={item.data.style} 
                    onChange={(dates)=>{
                      setNowDateS(dayjs(dates[0]))
                      setNowDateE(dayjs(dates[1]))
                    }}
                    onOpenChange={(open)=>{
                      if(!open){
                        return item.data.onChange([nowDateS,nowDateE],item.key)
                      }
                    }}
                  />
                )
              }else if(item.type === 'DateRange'){
                return (
                  <div key={item.key+'_'+ind}>
                     {
                       item.data !== undefined && item.data.length>0 &&
                       item.data.map((ele:selectItemType,index:number)=>{
                        if(index===0){
                          return (
                            <span key={item.key+'_span_'+ind}>
                              <DatePicker 
                              key={ele.key+dateYS} 
                              disabled={dateType === 'week' || compType=='2'?true:false} 
                              defaultValue={dateYS} 
                              format={dateFormat}
                              style={ele.data.style} 
                              picker={dateType} 
                              onChange={(date)=>{
                                return ele.data.onChange(date,ele.key)
                              }}
                              /> 
                              <span  key={ele.key+'_span_ele_'+index}  className={styles.timeFG}>-</span>
                            </span>
                          )
                        }else{
                          return (
                            <DatePicker 
                            key={ele.key+dateYE}
                            disabled={dateType === 'week' || compType=='1'?true:false} 
                            defaultValue={dateYE} 
                            format={dateFormat}
                            style={ele.data.style} 
                            picker={dateType} 
                            onChange={(date)=>{
                              return ele.data.onChange(date,ele.key)
                            }}
                            /> 
                          )
                        }
                       })
                     }
                  </div>
                )
              }
            })
          }
        </Space>
      </Col>
      <Col span={6}>
        <Space wrap size="middle">
          <Button type="link" icon={showMore?<DownOutlined /> : <UpOutlined/>} onClick={changeMore}>{showMore?'更多筛选':'收起更多'}</Button>
          <Button type="primary"  icon={<SearchOutlined />} onClick={()=>{onSearch(params)}}>查询</Button>
          <Button  icon={<ReloadOutlined /> } onClick={onReset}>恢复默认</Button>
        </Space>
      </Col>
    </Row>
  );
}

export default SearchArea;
